<?php

namespace App\Http\Controllers\api;

use App\Http\Controllers\common\BaseController;
use App\Http\Controllers\Controller;
use App\Models\LookHouseModel;
use App\Services\Curl;
use App\Services\EsService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class LookHouse extends Controller
{
    public static function create(Request $request){
        //验证数据
        $validator = Validator::make($request->all(), [
            'name'=>'required',
            'mobile'=>'required',
            'intention'=>'required'
        ]);
        $errors = $validator->errors()->toArray();
        if (!empty($errors)){
            return BaseController::retJson(500,$errors,null);
        }
        //找房需求入库
        $result=LookHouseModel::create($request->all());
        if ($result){
            try {
                $es=new EsService();
                //es入库
                 $es->add_doc($result->id,$request->all());
                return BaseController::retJson(2001,'发布成功',true);
            }catch (\Exception $e){
                return BaseController::retJson(2001,'Es添加失败',true);
            }
        }else{
            return BaseController::retJson(1001,'添加失败',null);
        }
    }
    public static function get_area(Request $request){
        $area_name = $request->get('area_name');
        $keyword = '住宅区';
        $request_url = sprintf(config('tencent_map.suggestion_url'),$area_name,$keyword,config('tencent_map.key'));
        $housesData = Curl::getRequest($request_url);
        $data = [];
        foreach ($housesData['data'] as $k => $v)
        {
            $arr = [
                'id' => $k,
                'houses_name' => $v['title'],
                'class' => 'chunk'
            ];
            array_push($data,$arr);
        }
        if (empty($data)){
            return BaseController::retJson(2000,'查询失败',true);
        }else{
            return BaseController::retJson(4001,'成功',$data);
        }
    }
}
